'use strict';

ionicTea.controller('accountCtrl', function ($scope, $rootScope, $state, UserService, $window, HttpService, $ionicActionSheet, $cordovaCamera, HttpUploadService, ShareService) {

    $scope.user = UserService.getUserAcceptCache();
    $scope.hasStore = false;
    $scope.blogList = [];

	var userCallback = {
		success: function success(user) {
			$scope.user = user;
      // global user
      $rootScope.teaUser = UserService.getUserAcceptCache();
  		$rootScope.unreadNotifyMessage = $rootScope.teaUser.new_message_count;

			$window.localStorage['user'] = JSON.stringify(user);
      $scope.hasStore = user.shop_list.length > 0;

			var callback = {
				success: function success(result) {
          //把图片处理成插件所需的格式
          var length = result.result.length;
          for(var i=0;i<length;i++){
            var imgs = result.result[i].imglist;
            //if(imgs.length == 0)continue;
            var items = [];
            for(var img in imgs){
              console.log("图片链接："+imgs[img]);
              var item = {
                src:imgs[img],
                thumb:imgs[img]
              };
              items.push(item);
            }

            result.result[i].imglist = items;
          }
		  $scope.isStop_scroll = false;
          $scope.blogList = result.result;
          console.log("嚯嚯嚯 看看");console.log($scope.blogList);
				},
				failed: function failed(err) {
					console.log(err.statusText);
				}
			};

			// HttpService({ name: 'blog/list', params: {user_id: user.id, page: 1}, callback:callback});
			HttpService({ name: 'blog/list', params: { page: 1, user_id: user.id,viewer_id: user.id }, callback: callback });
		}
	};

	//滚动加载茶谈
	$scope.currPage = 1;
	$scope.isStop_scroll = true;
	$scope.scroll_load_talk = function(){
		$scope.currPage += 1;

		var param = {page: $scope.currPage};

		var user = UserService.getUserAcceptCache();
		if(user){
			param.viewer_id = user.id;
			param.user_id = user.id;
		}
	  	var callback = {
			success: function success(result) {

				console.log("茶谈加载完毕");
				console.log(result);
				//把图片处理成插件所需的格式
				var length = result.result.length;
				if(length == 0){
					$scope.isStop_scroll = true;
					return;
				}

				for(var i=0;i<length;i++){
					var imgs = result.result[i].imglist;
					//if(imgs.length == 0)continue;
					var items = [];
					for(var img in imgs){
						var item = {
							src:imgs[img],
							thumb:imgs[img]
						};
						items.push(item);
					}
					result.result[i].imglist = items;
					$scope.blogList.push(result.result[i]);
				}
				//结束加载动画
				$scope.$broadcast('scroll.infiniteScrollComplete');
			},
			failed: function failed(err) {
				console.log(err.statusText);
				//结束加载动画
				$scope.$broadcast('scroll.infiniteScrollComplete');
			}
		};

		console.log("滚动 加载茶谈  记住是茶谈 参数："+JSON.stringify(param));

		HttpService({ name: 'blog/list',params:param,callback: callback });
	}

  $scope.deleteTeaTalk = function(blog_id) {
    var callback = {
      success: function success(result) {
        UserService.getUserMustRefresh(userCallback);
      },
      failed: function failed(err) {
        alert(err);
      }
    };

    // HttpService({ name: 'blog/list', params: {user_id: user.id, page: 1}, callback:callback});
    HttpService({ name: 'blog/delete',
      params: {
        blog_id: blog_id,
        user_id: $scope.user.id,
      }, callback: callback });
  };

  // 茶谈的功能 start
  //关注用户
  $scope.follow_user = function (follower_id) {
    var user = UserService.getUserAcceptCache();
    if (!user) return;

    var param = {
      user_id:user.id,
      follower_id:follower_id
    };

    console.log("关注用户："+JSON.stringify(param));

    var callback = {
      success: function success(data) {
        console.log("关注茶谈用户返回:");console.log(data);
        alert('关注成功');
      }
    };
    HttpService({ name: 'user/follow', params: param, callback: callback });
  };

  /*茶谈点赞*/
  $scope.talk_upvote = function (blog) {
    var user = UserService.getUserAcceptCache();
    if (!user) return;

    var param = {
      user_id:user.id,
      blog_id:blog.id
    };

    console.log("茶谈点赞："+JSON.stringify(param));

    var callback = {
      	success: function success(data) {
        	console.log("茶谈点赞返回:");console.log(data);
        	if(data.code == 200){
        		blog.is_upvote = true;
        		blog.up_count += 1;
        	}
      	}
    };
    HttpService({ name: 'blog/upvote', params: param, callback: callback });
  }

  //取消茶谈点赞
	$scope.talk_upvote_cancel = function (blog) {
		var user = UserService.getUserAcceptCache();
		if (!user) return;

		var param = {
			user_id:user.id,
			blog_id:blog.id
		};

		console.log("茶谈取消点赞："+JSON.stringify(param));

		var callback = {
			success: function success(data) {
				console.log("茶谈取消点赞返回:");console.log(data);
				if(data.code == 200){
	        		blog.is_upvote = false;
	        		blog.up_count -= 1;
	        	}
			}
		};
		HttpService({ name: 'blog/upvote/cancel', params: param, callback: callback });
	}

  //跳转茶谈评论
  $scope.goto_talk_comntent = function (blogId) {

    $state.go("talk-comment", { blog_id: blogId });
  };

  // 分享
	$scope.tea_talk_share = function (talkItem) {
	    var shareImgArray = [];
	    var pos = 0;
	    var size = talkItem.imglist.length;

	    if (size != null && size>0) {
	        for(;pos < size; pos++) {
                shareImgArray.push(talkItem.imglist[pos].src);
            }
            ShareService.shareImgMsg(talkItem.content, shareImgArray);
	    } else {
	        ShareService.share(talkItem.content);
	    }
	};
  // 茶谈的功能 end

	$scope.goToUserDetailPage = function (id) {
		UserService.goToUserDetailPage(id);
	};

	$scope.initDatas = function () {
		UserService.getUserMustRefresh(userCallback);
	};

	$scope.goToMyCollection = function () {
		$state.go('account-my-collection');
	};

	$scope.goToTeaB = function () {
		$state.go('account-tea-b-exchange');
	};

	$scope.goToSign = function () {
		$state.go('account-sign');
	};

	$scope.goToShopCart = function () {
		$state.go('account-shop-cart');
	};

	var avatarSetCallback = {
    	    success: function() {
                alert('修改头像成功');
                $state.go('setting-personal');
    	    },
    	    failed: function() {
    	        alert('修改头像失败，请尝试重新选择图片。');
    	        $state.go('setting-personal');
    	    },
    	};

    var avatarUploadCallback = {
        success: function(url) {
//            $scope.user.avatar = url;
            HttpService({name: 'user/set', params: { user_id: $scope.user.id, avatar: url }, callback: avatarSetCallback});

        },
        failed: function() {
            alert('选择图片失败，请重试。');
        },
    };

    // 修改头像
    //选择相册或者拍照
    $scope.selectImgType = function () {

        // 显示操作表
        $ionicActionSheet.show({
            cssClass: "user-sheet",
            buttons: [{ text: '拍照' }, { text: '从相册选择' }],
            titleText: '选择图片',
            cancelText: '取消',
            buttonClicked: function buttonClicked(index) {
                if (index == 0) {
                    $scope.takePhoto();
                }
                if (index == 1) {
                    $scope.from_gallery();
                }
                return true;
            }
        });
    };

    //相册选择
    $scope.from_gallery = function () {

        // destinationType: Camera.DestinationType.FILE_URI,
        var options = {
            targetWidth: 200, //照片宽度
            targetHeight: 200, //照片高度
            sourceType: Camera.PictureSourceType.SAVEDPHOTOALBUM,
        };

        $cordovaCamera.getPicture(options).then(function (imageURI) {
            HttpUploadService.upload(imageURI, avatarUploadCallback, false);
        }, function (err) {
            // error
        });
    };

    //拍照
    $scope.takePhoto = function () {

        var options = {
            quality: 100, //相片质量0-100
            destinationType: Camera.DestinationType.FILE_URI, //返回类型：DATA_URL= 0，返回作为 base64 編碼字串。 FILE_URI=1，返回影像档的 URI。NATIVE_URI=2，返回图像本机URI (例如，資產庫)
            sourceType: Camera.PictureSourceType.CAMERA, //从哪里选择图片：PHOTOLIBRARY=0，相机拍照=1，SAVEDPHOTOALBUM=2。0和1其实都是本地图库
            allowEdit: false, //在选择之前允许修改截图
            encodingType: Camera.EncodingType.JPEG, //保存的图片格式： JPEG = 0, PNG = 1
            targetWidth: 200, //照片宽度
            targetHeight: 200, //照片高度
            mediaType: 0, //可选媒体类型：圖片=0，只允许选择图片將返回指定DestinationType的参数。 視頻格式=1，允许选择视频，最终返回 FILE_URI。ALLMEDIA= 2，允许所有媒体类型的选择。
            cameraDirection: 0, //枪后摄像头类型：Back= 0,Front-facing = 1
            popoverOptions: CameraPopoverOptions,
            saveToPhotoAlbum: true
        };

        $cordovaCamera.getPicture(options).then(function (imageURI) {
            HttpUploadService.upload(imageURI, avatarUploadCallback, false);
        }, function (err) {

        });
    };

	$scope.goToLogin = function () {
		$state.go('account-login');
	};

	$scope.goToMsg = function () {
		$state.go('account-msg');
	};

	$scope.goToPointExchange = function () {
		$state.go('account-point-exchange');
	};
});

ionicTea.controller('loginCtrl', function ($scope, $rootScope, $state, $window, $ionicPopup, HttpService, md5, MsgService) {

	$scope.goToTabAccount = function () {
		$state.go('tab.account');
	};

	$scope.goToRegister = function () {
		$state.go('account-register');
	};

	$scope.goToFindPSWBack = function () {
		$state.go('account-find-psw-back');
	};

	var initRong = function initRong(token) {
		console.log('RongCloud connect token = ' + tokne);
		RongCloudLibPlugin.init({
			appKey: 'mgb7ka1nbzewg' }, function (ret, err) {
			if (ret.status == 'error') alert(err.code);
			console.log('RongCloud connect error = ' + err.code);
		});

		RongCloudLibPlugin.connect({
			token: token }, function (ret, err) {
			if (ret.status == 'success') alert(ret.result.userId);
			console.log('RongCloud connect success = ' + ret.result.userId);
		});

		RongCloudLibPlugin.setConnectionStatusListener(function (ret, err) {
			if (ret) {
				alert(JSON.stringify(ret));
				console.log('setConnectionStatusListener:' + JSON.stringify(ret));
				if (ret.result.connectionStatus == 'KICKED') {
					/* alert('您的帐号已在其他端登录!');
      $rootScope.hideTabs = false;
      $ionicHistory.clearCache();
      $state.go('login');*/
				}
			}
			if (err) {
				console.log('setConnectionStatusListener error:' + JSON.stringify(err));
			}
		});
	};

	$scope.back = function() {
		$state.go('tab.main');
	};


	$scope.login = function (mobile, password) {

		// An alert dialog
		function showAlert(msg) {
			var alertPopup = $ionicPopup.alert({
				title: '万茶帮',
				template: msg,
        cancelText: '取消',
        okText: '确定',
			});

			alertPopup.then(function (res) {
				console.log('fuck yeah!');
			});
		};

		if (mobile == null || mobile.length < 11) {
			showAlert('请输入正确的手机号!');
			return;
		}

		password = md5.createHash(password);

		var callback = {
			success: function success(data) {
				console.log('登陆成功');
				$window.localStorage['user'] = JSON.stringify(data);
				$window.localStorage['token'] = data.token;
				$state.go('tab.account', {}, { reload: true });
				// initRong(data.token);
				MsgService.initRongCloud();
			},
			failed: function failed(err) {
				console.log(err);
				showAlert(err);
			}
		};

		HttpService({ name: 'account/login', params: { mobile: mobile, password: password }, callback: callback });
		// var data = {};
		// var nim = NIM.getInstance({
		//     // debug: true,
		//     appKey: '511163fd0da076b73403334b56988081',
		//     account: '18502818214',
		//     token: '66ff7ef87ad57b2d62e7e33835dda605',
		//     onconnect: onConnect,
		//     onwillreconnect: onWillReconnect,
		//     ondisconnect: onDisconnect,
		//     onerror: onError
		// });
		// function onConnect() {
		//     console.log('连接成功');
		// }
		// function onWillReconnect(obj) {
		//     // 此时说明 SDK 已经断开连接, 请开发者在界面上提示用户连接已断开, 而且正在重新建立连接
		//     console.log('即将重连');
		//     console.log(obj.retryCount);
		//     console.log(obj.duration);
		// }
		// function onDisconnect(error) {
		//     // 此时说明 SDK 处于断开状态, 开发者此时应该根据错误码提示相应的错误信息, 并且跳转到登录页面
		//     console.log('丢失连接');
		//     console.log(error);
		//     if (error) {
		//         switch (error.code) {
		//         // 账号或者密码错误, 请跳转到登录页面并提示错误
		//         case 302:
		//             break;
		//         // 被踢, 请提示错误后跳转到登录页面
		//         case 'kicked':
		//             break;
		//         default:
		//             break;
		//         }
		//     }
		// }
		// function onError(error) {
		//     console.log(error);
		// }
	};
});

ionicTea.controller('registerCtrl', function ($scope, $state, $ionicPopup, $window, HttpService, md5) {

	var smsCode = '';

	// An alert dialog
	function showAlert(msg) {
		var alertPopup = $ionicPopup.alert({
			title: '万茶帮',
			template: msg
		});

		alertPopup.then(function (res) {
			console.log('fuck yeah!');
		});
	};

	$scope.getCode = function (mobile, isFindPswBack) {

		if (mobile == null || mobile.length < 11) {
			showAlert('请输入正确的手机号!');
			return;
		}

		var callback = {
			success: function success(data) {
				smsCode = data.code;
			},
			failed: function failed(err) {
				showAlert(err);
			}
		};

		if (isFindPswBack == null) {
			HttpService({ name: 'sms/reg_verifycode', params: { mobile: mobile }, callback: callback });
		} else {
			HttpService({ name: 'sms/getpwd_verifycode', params: { mobile: mobile }, callback: callback });
		}
	};

	$scope.register = function (mobile, verifycode, password, password2, isFindPswBack) {

		if (mobile == null || mobile.length < 11) {
			showAlert('请输入正确的手机号!');
			return;
		}

		if (password === password2) {} else {
			showAlert('两次输入的密码不一样!');
			return;
		}

		password = md5.createHash(password2);

		var callback = {
			success: function success(data) {
				console.log('注册成功');
				$window.localStorage['user'] = JSON.stringify(data);
				if (isFindPswBack) {
					$state.go('account-login');
				} else {
					$state.go('tab.account');
				}
			},
			failed: function failed(err) {
				console.log(err);
				showAlert(err);
			}
		};

		if (isFindPswBack == null) {
			HttpService({ name: 'account/reg', params: { mobile: mobile, verifycode: verifycode, password: password }, callback: callback });
		} else {
			HttpService({ name: 'account/setpwd', params: { mobile: mobile, verifycode: verifycode, password: password }, callback: callback });
		}
	};
});

ionicTea.controller('collectCtrl', function ($scope, $state) {
	$scope.goToActivityNotify = function () {
		$state.go('notify-activity');
	};

	$scope.goToMyAward = function () {
		$state.go('notify-my-award');
	};

	$scope.goToNewNotify = function () {
		$state.go('new-notify');
	};
	//切换按钮
	$scope.shop_area = true;
	$scope.goods_area = false;

	$scope.changeToShop = function () {
		$scope.shop_area = true;
		$scope.goods_area = false;
	};

	$scope.changeToGoods = function () {
		$scope.shop_area = false;
		$scope.goods_area = true;
	};
});

ionicTea.controller('teaBCtrl', function ($scope, $state, $ionicPopup, HttpServiceForNew, UserService) {

  $scope.userInfo = UserService.getUserAcceptCache();
	//切换按钮
	$scope.tea_b_area = false;
	$scope.get_b_area = true;

	$scope.changeToTeaB = function () {
		$scope.tea_b_area = true;
		$scope.get_b_area = false;
	};

	$scope.changeToGetB = function () {
		$scope.tea_b_area = false;
		$scope.get_b_area = true;
	};

	$scope.goToSuccessfulList = function () {
		$state.go('account-tea-b-exchange-successful-list');
	};

  $scope.getPointList = function () {
    var param = {
      user_id: $scope.userInfo.id,
    };

    var callback = {
      success: function success(data) {
        console.log("积分列表返回");
        console.log(data);
        $scope.pointList = data;
      },
      failed: function failed(err) {}
    };

    HttpServiceForNew({ name: 'points/point_list', params:param, callback: callback, type: 'GET'});
	};

	// Triggered on a button click, or some other target
	$scope.showPopup = function () {
		$scope.data = {};

		$scope.press_point = '2000';

		// An elaborate, custom popup
		var myPopup = $ionicPopup.show({
			templateUrl: 'templates/account/dialog/rush-buy-dialog.html',
			scope: $scope
		});

		myPopup.then(function (res) {});

		$scope.onRushBuyClick = function () {
			myPopup.close();
		};
	};
});

ionicTea.controller('shopCartCtrl', function ($scope, $rootScope, $state, $stateParams, $ionicPopup, UserService, HttpService) {

	$scope.currentPos = 0;
	$scope.list = ['1', '2'];

	$scope.shopList = [''];

	if ($stateParams.userInfo != null) {
		$scope.userInfo = $stateParams.userInfo;
	} else {
		$scope.userInfo = UserService.getUserAcceptCache();
	}

	$scope.isShow = function (pos) {
		return $scope.currentPos === pos;
	};

	$scope.changeCurrent = function (pos) {
		$scope.isShowPayButton = pos === 0;
		$scope.currentPos = pos;
	};

	$scope.isShowPayButton = true;

	// 地址选择
	$scope.goToChooseAddress = function () {
		$state.go('setting-address', { isChooseAddress: true, from_url: 'account-shop-cart' });
	};

	// 待支付
	$scope.goToNoPay = function () {
		$state.go('account-shop-cart-no-pay');
	};
	// 待发货
	$scope.goToNoTransport = function () {
		$state.go('account-shop-cart-no-transport');
	};
	// 物流中
	$scope.goToWuLiuList = function () {
		$state.go('account-shop-cart-wuliu-list');
	};
	// 物流信息
	$scope.goToWuLiu = function (item) {
		$state.go('account-shop-cart-wuliu', {item: item});
	};
	// 购物记录
	$scope.goToHistory = function () {
		$state.go('account-shop-cart-history');
	};

	//初始化 订单页面
	$scope.order_list = [];
	//0：未付款, 1：已付款, 2：已发货,  3：已收货， 4：退款申请， 5：已退款

	$scope.init_order = function(flag){
		$scope.currPage = 1;
		$scope.isStop_scroll = true;

		var user = UserService.getUserAcceptCache(true);
		if(!user)return;

		var param = {
			user_id: user.id,
			status:flag
		};

		console.log("加载订单参数："+JSON.stringify(param));
		var callback = {
			success: function success(data) {
				console.log("订单返回");console.log(data);
				$scope.order_list = data.result;
				$scope.isStop_scroll = false;
			},
			failed: function failed(err) {}
		};

		HttpService({ name: 'order/list',params:param,callback: callback});
	}

	$scope.scroll_load_order = function(flag){

		var user = UserService.getUserAcceptCache(true);
		if(!user)return;

		$scope.currPage += 1;

		var param = {
			user_id: user.id,
			page: $scope.currPage,
			status:flag
		};

		console.log("滚动加载订单参数："+JSON.stringify(param));

		var callback = {
			success: function success(data) {
				console.log("订单返回");console.log(data);
				var length = data.result.length;
				if(length == 0){
					$scope.isStop_scroll = true;
					return;
				}
				for(var i=0;i<length;i++){
					$scope.order_list.push(data.result[i]);
				}
				$scope.$broadcast('scroll.infiniteScrollComplete');
			},
			failed: function failed(err) {}
		};

		HttpService({ name: 'order/list',params:param,callback: callback});
	}

	//订单分页
	$scope.currPage = 1;
	$scope.isStop_scroll = true;

	//去支付
	$scope.to_pay = function(item){
		alert(item.sn);
	}

	// 删除购物车物品
	$scope.showShopDeleteConfirm = function (id) {
		var confirmPopup = $ionicPopup.confirm({
			title: '万茶帮',
			template: '是否要移除该商品?',
      cancelText: '取消',
      okText: '确定',
		});

		confirmPopup.then(function (res) {
			if (res) {
				deleteShop(id);
			} else {}
		});
	};

	// 地址 删除地址
	function deleteShop(id) {
		var user = UserService.getUserAcceptCache();
		var callback = {
			success: function success(data) {
				$scope.getShopList();
			},
			failed: function failed(err) {}
		};

		HttpService({ name: 'shopcart/remove',
			params: {
				user_id: user.id,
				product_id: id
			}, callback: callback });
	}

	//记得穿参数
	$scope.goto_orderConfirm = function () {
		var orderInfo = {};
		// orderInfo.userInfo = $scope.userInfo;
		orderInfo.userInfo = null;
		var productsArray = [];
		var size = $scope.shopList.length;
		var i = 0;
		for (i = 0; i < size; i++) {
			var p = $scope.shopList[i];
      if (!p.isSelected) continue;
			productsArray.push({
				count: p.number,
				id: p.product.id,
				name: p.product.name,
				sale_price: p.product.sale_price,
				shop_logo: p.product.shop.logo,
				shop_name: p.product.shop.name,
			});
		}
		orderInfo.products = productsArray;

    if (productsArray.length == 0) {
      $rootScope.alert_err("没有选中的商品");
      return;
    }

		$state.go("product-orderConfirm", { from_url: 'account-shop-cart', orderInfo: orderInfo });
	};

	var calcCount = function() {
		//计算下辣鸡合计
		var products = $scope.shopList;
		var all = 0;
		for (var i = 0; i < products.length; i++) {
			all += products[i].number * products[i].product.sale_price;
		}
		$scope.count_price = all;
	};

  $scope.select = function(shop){
    shop.isSelected = !shop.isSelected;
  };

	$scope.getShopList = function () {

		$scope.loginUser = UserService.getUserAcceptCache();

		var callback = {
			success: function success(data) {
				$scope.shopList = data.result;
        for (var pos=0; pos<$scope.shopList.length;pos++) {
          $scope.shopList[pos].isSelected = true;
        }
				//设置监听
				$scope.$watch('shopList', calcCount, true);
			},
			failed: function failed(err) {}
		};

		HttpService({ name: 'shopcart/list', params: { user_id: $scope.loginUser.id }, callback: callback });
	};
});

ionicTea.controller('otherAccountCtrl', function ($scope, $state,$rootScope, $stateParams, HttpService, UserService, ShareService, $ionicHistory) {

	var userId = $stateParams.id;

	var loginUser = UserService.getUserAcceptCache();

	$scope.user = null;
	$scope.isFriends = false;
	$scope.isFollow = false;
	$scope.hasStore = false;
	$scope.followText = "+关注";

	var blogCallback = {
		success: function success(result) {
		    //把图片处理成插件所需的格式
		    var length = result.result.length;
		    for(var i=0;i<length;i++){
		        var imgs = result.result[i].imglist;
		        //if(imgs.length == 0)continue;
		        var items = [];
		        for(var img in imgs){
		          	console.log("图片链接："+imgs[img]);
		          	var item = {
		            	src:imgs[img],
		            	thumb:imgs[img]
		          	};
		          	items.push(item);
		        }
		        console.log("格式转换后："+JSON.stringify(items));
		        result.result[i].imglist = items;
		    }

			$scope.blogList = result.result;
			console.log("个人主页 茶谈");console.log($scope.blogList);
		},
		failed: function failed(err) {
			console.log(err.statusText);
		}
	};

	if (userId != null) {
		var userCallback = {
			success: function success(user) {
				console.log("加载用户信息：");console.log(user);
				$scope.user = user;
				$scope.isFollow = user.is_follow;
				if($scope.isFollow){
					$scope.followText = "取消关注";
				}else{
					$scope.followText = "+关注";
				}

				$scope.isFriends = user.is_friend;
		        $scope.isFollow = user.is_follow;
		        $scope.hasStore = user.shop_list.length > 0? true: false;

		        if ($scope.isFollow) {
		          $scope.followText = "取消关注";
		        } else {
		          $scope.followText = "+关注";
		        }
        		var login_user = UserService.getUserAcceptCache();
        		var param = {page: 1,user_id: user.id};
        		if(login_user)param.viewer_id = login_user.id;

				HttpService({ name: 'blog/list', params: param, callback: blogCallback });
			},
			failed: function failed(err) {}
		};

		HttpService({ name: 'user/show', params: { target_id: userId, user_id: loginUser.id }, callback: userCallback });
	}

	$scope.back = function () {
		//$state.backToLastView();
		$rootScope.back();
	};

	$scope.goToUserDetailPage = function (id) {
		UserService.goToUserDetailPage(id);
	};

  //商品详情进入店铺
	$scope.gotoStore = function (id) {
		$state.go('store', { store_id: id }, { reload: true });
	};

	$scope.addFriends = function (id) {
		var userCallback = {
			success: function success() {
				$scope.isFriends = !$scope.isFriends;
				if ($scope.isFriends) {
					alert('添加好友成功');
				} else {
					alert('删除好友成功');
				}
			},
			failed: function failed(err) {}
		};

		var url = 'user/friend/add';

		if ($scope.isFriends) {
			url = 'user/friend/delete';
		}

		HttpService({ name: url, params: { user_id: loginUser.id, friend_id: id }, callback: userCallback });
	};

	$scope.goToChatPage = function () {

    RongCloudLibPlugin.clearMessagesUnreadStatus({
            conversationType: 'PRIVATE',
            targetId: $scope.user.id,
        }, function (ret, err) {
            // alert(ret.status);
    });

		UserService.goToChatPage($scope.user.id);
	};

  //关注用户
  $scope.isFollow = false;
  $scope.follow_user = function (follower_id) {
    var user = UserService.getUserAcceptCache();
    if (!user) return;

    var param = {
      user_id:user.id,
      follower_id:follower_id
    };

    console.log("关注用户："+JSON.stringify(param));

    var callback = {
      success: function success(data) {
        console.log("关注茶谈用户返回:");console.log(data);

        if ($scope.isFollow) {
            $rootScope.alert_suc("已取消关注");
        } else {
            $rootScope.alert_suc("关注成功");
        }

        $scope.isFollow = !$scope.isFollow;


        if ($scope.isFollow) {
          $scope.followText = "取消关注";
        } else {
          $scope.followText = "+关注";
        }
      }
    };

    if ($scope.isFollow) {
        HttpService({ name: 'user/follow/cancel', params: param, callback: callback });
    } else {
        HttpService({ name: 'user/follow', params: param, callback: callback });
    }

  };

  /*茶谈点赞*/
  $scope.talk_upvote = function (blog) {
    var user = UserService.getUserAcceptCache();
    if (!user) return;

    var param = {
      user_id:user.id,
      blog_id:blog.id
    };

    console.log("茶谈点赞："+JSON.stringify(param));

    var callback = {
      	success: function success(data) {
        	console.log("茶谈点赞返回:");console.log(data);
        	if(data.code == 200){
        		blog.is_upvote = true;
        		blog.up_count += 1;
        	}
        	/*HttpService({ name: 'blog/list', params: { page: 1, user_id: userId }, callback: blogCallback });*/
      	}
    };
    HttpService({ name: 'blog/upvote', params: param, callback: callback });
  }

  //取消茶谈点赞
	$scope.talk_upvote_cancel = function (blog) {
		var user = UserService.getUserAcceptCache();
		if (!user) return;

		var param = {
			user_id:user.id,
			blog_id:blog.id
		};

		console.log("茶谈取消点赞："+JSON.stringify(param));

		var callback = {
			success: function success(data) {
				console.log("茶谈取消点赞返回:");console.log(data);
				if(data.code == 200){
	        		blog.is_upvote = false;
	        		blog.up_count -= 1;
	        	}
			}
		};
		HttpService({ name: 'blog/upvote/cancel', params: param, callback: callback });
	}

  //跳转茶谈评论
  $scope.goto_talk_comntent = function (blogId) {
    $state.go("talk-comment", { blog_id: blogId ,user_is_followed:$scope.isFollow });
  };

  // 分享
	$scope.tea_talk_share = function (talkItem) {
	    var shareImgArray = [];
	    var pos = 0;
	    var size = talkItem.imglist.length;

	    if (size != null && size>0) {
	        for(;pos < size; pos++) {
                shareImgArray.push(talkItem.imglist[pos].src);
            }
            ShareService.shareImgMsg(talkItem.content, shareImgArray);
	    } else {
	        ShareService.share(talkItem.content);
	    }
	};
});

ionicTea.controller('orderCtrl', function ($scope, $state, $stateParams, $ionicPopup, $timeout, HttpService, UserService) {

  $scope.showCancelDialog = function() {
    $ionicPopup.prompt({
       title: '确认取消订单',
       template: '请选择您取消订单的原因',
       inputType: 'text',
       inputPlaceholder: '取消原因',
       cancelText: '取消',
       okText: '确定',
     }).then(function(res) {
       console.log('你填写内容为', res);
     });
  };

  $scope.showProductGiveBackDialog = function() {
    $scope.data = {
      company: '顺丰快递',
    };

    // An elaborate, custom popup
    var myPopup = $ionicPopup.show({
      templateUrl: 'templates/account/order/order-cancel-dialog.html',
      title: '填写物流信息',
      subTitle: '请填写您退货的物流信息',
      scope: $scope,
      buttons: [
        { text: '取消' },
        {
          text: '<b>确定</b>',
          type: 'button-positive',
          // onTap: function(e) {
          //   if (!$scope.data.wifi) {
          //     //don't allow the user to close unless he enters wifi password
          //     e.preventDefault();
          //   } else {
          //     return $scope.data.wifi;
          //   }
          // }
        }
      ]
    });

    myPopup.then(function(res) {
      console.log('Tapped!', res);
    });

    // $timeout(function() {
    //    myPopup.close(); //close the popup after 3 seconds for some reason
    // }, 3000);
  }
});

ionicTea.controller('wuliuCtrl', function ($scope, $state, $stateParams, HttpService, UserService, KuaiDiService) {


	$scope.init = function() {
		$scope.item = $stateParams.item;
		var callback = {
			success: function(data) {
				$scope.wuliuLink = data;
			},
			failed: function(e) {
				alert(e);
			},
		}

		KuaiDiService.getKuaiDiUrl('402092113344','shentong',callback);
	};


});

ionicTea.controller('accountCollectionCtrl', function ($scope, $state, HttpService, UserService) {
	//切换按钮  功能 待封装
	$scope.isCollectStore = true;
	$scope.isCollectProduct = false;
  $scope.isCollectRealStore = false;
	var user_id = UserService.getUserAcceptCache().id;

	$scope.changeToStore = function () {
		$scope.isCollectStore = true;
		$scope.isCollectProduct = false;
    $scope.isCollectRealStore = false;

		var callback = {
			success: function success(result) {
				$scope.storeList = result;
			},
			failed: function failed(err) {}
		};

		HttpService({ name: 'user/favorite', params: {
				user_id: user_id,
				type: 'shop'
			}, callback: callback });
	};

	$scope.changeToProduct = function () {
		$scope.isCollectStore = false;
		$scope.isCollectProduct = true;
    $scope.isCollectRealStore = false;

		var callback = {
			success: function success(result) {
				$scope.productList = result;
			},
			failed: function failed(err) {}
		};

		HttpService({ name: 'user/favorite', params: {
				user_id: user_id,
				type: 'product'
			}, callback: callback });
	};

  $scope.changeToRealStore = function () {
    $scope.isCollectStore = false;
		$scope.isCollectProduct = false;
    $scope.isCollectRealStore = true;

		var callback = {
			success: function success(result) {
				$scope.realStoreList = result;
			},
			failed: function failed(err) {}
		};

		HttpService({ name: 'user/favorite', params: {
				user_id: user_id,
				type: 'teahouse'
			}, callback: callback });
	};

  /*进入茶馆**/
	$scope.goto_shop = function (item) {

		$state.go("tea-shop", { id: item.id }, {});
	};

  // 商品详情
  $scope.goto_product_info = function (product_id) {
		$state.go('product-info', { product_id: product_id });
	};

  // 店铺详情
  //商品详情进入店铺
	$scope.product_goto_store = function (id) {

		$state.go('store', { store_id: id }, { reload: true });
	};
});
